;(function($) {
	"use strict";
	$.fn.bgsl = function(o) {
		var defaults = {
			animduration : 600,
			animspeed    : 10000
		};
		var settings = $.extend({}, defaults, o);

		var $wrapper = this,
		$slider = $wrapper.find('ul.bgsl'),
		$slides = $slider.children('li');

		var state = {
			slidecount : $slides.length,
			animating : false,
			paused : false,
			currentslide : 1,
			nextslide : 0,
			currentindex : 0,
			nextindex : 0,
			direction : 1,
			interval : null
		};

		var init = function() {
			$slides.addClass('bgsl-slide');
			$slides.hide();			
			$slides.eq(state.currentindex).show();
			go();
		}

		var go = function() {
			if(!state.animating){
				state.animating = true;
				setnext();
				var direction;
				if(state.direction==1){
					direction = {top: ($wrapper.height()-$slider.height())};
					state.direction=2;
				}else if(state.direction==2){
					direction = {top: 0};
					state.direction=3;
				}else if(state.direction==3){
					direction = {left: ($wrapper.width()-$slider.width())};
					state.direction=4;
				}else if(state.direction==4){
					direction = {left: 0};
					state.direction=1;
				}

				
				$slider.animate(direction, defaults.animspeed, function() {
					$slides.eq(state.nextindex).fadeIn(defaults.animduration);
					$slides.eq(state.currentindex).fadeOut(defaults.animduration, function(){
						state.animating = false;
						state.currentslide = state.nextslide;
						state.currentindex = state.nextindex;
						go();
					});
				});
			}
		}

		var setnext = function(){
			if($slides.eq(state.currentindex).next().length){
				state.nextindex = state.currentindex + 1;
				state.nextslide = state.currentslide + 1;
			}
			else{
				state.nextindex = 0;
				state.nextslide = 1;
			}
		}
		
		init();
	};
})(jQuery);